package mannA1.controller;

import javax.swing.JTextField;


import mannA1.model.Model;
import mannA1.view.A1GUI;

/** Controller to deal with inputing choices into the JTextFields.*/
public class InsertChoicesController {
	
	Model model;
	A1GUI a1gui;
	int position;
	
	public InsertChoicesController (A1GUI a1gui, Model m, int position) {
		this.model = m;
		this.a1gui = a1gui;
		this.position = position;
	}
	
	/** Checks to make sure that choices are valid.*/
	public void process() {
			
			String choice = a1gui.getChoice(position).getText();
			checkValidChoice(choice, position);
			
			/**If the choice is valid, the model is updated.  For true or false, the gui is updated. */
			if (checkValidChoice(choice, position))
			{
				model.lines[position].choice = choice;
			}
			a1gui.choices[position].setText(model.lines[position].choice);		
	}

	/** Called by process, checks that choice is not blank or identical to another choice.
	 * @return true if passes checks for being blank or identical to another choice.
	 * */
	private boolean checkValidChoice(String choice, int j)
	{
		
		if (choice == null || choice.length() == 0)
		{
			System.err.println("Please do not leave choice blank.");//return error message here, empty choice
			return false;
		}

		for (int t = 0; t < model.numLines; t++)
		{
			if (a1gui.choices[t].getText().equals(a1gui.choices[j].getText()) && t != j)
			{
				System.err.println("This is the same choice as before.  Give yourselves variety, change your choice.");
				return false;
			}	
		}	
		model.lines[j].choice = a1gui.getChoice(j).getText(); //assign value from JtextField to Line
		return true;
	}
	
	/** Called when button is clicked, checks to see if all choices are valid.
	 * If not, return without doing anything, if so, set Editable of all to false.
	 * If valid, Lines are also assigned a value for choice based on the jTextField.*/
	public void noMoreChoices()
	{
		for (int t = 0; t < model.numLines; t++)
		{
			String choice = a1gui.getChoice(t).getText();
			
			if (checkValidChoice(choice, t) == false)
			{
				return;
			}
		}
		
		for (int t = 0; t < model.numLines; t++)
		{
			a1gui.choices[t].setEditable(false);
			model.lines[t].choice = a1gui.getChoice(t).getText();
		}
	}
}
